<?php
namespace App\Admin\Controllers\Quality;

use App\Admin\Ajax\Quality\FBACustomerReturnAjax;
use App\Models\Amazon\FbaCustomerReturn;
use App\Models\Basics\SysCountry;
use App\Models\Basics\SysICountry;
use App\Models\Basics\SysPlatAccount;
use App\Models\Product\ProductSku;
use App\Models\Quality\QDictTag;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Support\Facades\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;
class FBACustomerReturnController extends AdminController{

    protected $title = '退货报表FBA';

    protected $filters = [
        'start_date' => null,
        'end_date' => null,
        'order_id' => null,
        'account_id' => null,
        'country_id' => null,
        'status' => null,
    ];

    protected function grid()
    {
        $filtersField = array_keys($this->filters);
        $filters = $this->_getFilters($filtersField);
        $this->_initFilters($filters);
        $query = $this->_initQuery($filters);
        $paginator = $this->_paginator($query);
        $action = getAction($filtersField);
        $filtersBlade = [];
        $filtersBlade['start_date'] = $this->filters['start_date'];
        $filtersBlade['end_date'] = $this->filters['end_date'];
        $filtersBlade['order_id'] = $this->filters['order_id'];
        $filtersBlade['status'] = getOptions(FbaCustomerReturn::$_statusOption,$this->filters['status']);
        $filtersBlade['country_id'] = getOptions(SysICountry::options(),$this->filters['country_id']);
        $filtersBlade['account_id'] = getOptions(SysPlatAccount::options(),$this->filters['account_id']);
        $downloadUrl = '/xqc/quality/fba-customer-return-download?' . http_build_query(array_merge(Request::all(),['_export_' => true]));
        return view('quality.fba-customer-return.index', compact('paginator','filtersBlade','action','downloadUrl'));
    }

    private function _getFilters($filtersField){
        $filters = [];
        foreach ($filtersField as $field){
            $filters[$field] = request($field);
        }
        return $filters;
    }

    private function _initFilters($filters){
        foreach ($filters as $field => $filter){
            $this->filters[$field] = $filter;
        }
    }

    private function _initQuery($filters){
        //$query = FbaCustomerReturn::query()->orderBy('return_date','DESC');
        $query = FbaCustomerReturn::query()->where('status','<>',2)->orderBy('return_date','DESC');
        foreach ($filters as $field => $filter){
            if(is_null($filter))continue;
            if($field == 'start_date'){
                $query->where('return_date','>=',$filter . ' 00:00:00');
            }
            if($field == 'end_date'){
                $query->where('return_date','<=',$filter . ' 23:59:59');
            }
            if(in_array($field,['country_id','order_id','account_id','status'])){
                $query->where($field,$filter);
            }
        }
        return $query;
    }

    private function _paginator($query){
        return $query->paginate((int) (request("per_page",10)))->appends(Request::input());
    }

    public function ajax(){
        $action = request('action');
        $param = request('param');
        $ajax = new FBACustomerReturnAjax();
        return $param ? call_user_func([$ajax,$action],$param) : call_user_func([$ajax,$action]);
    }

    public function modal(){
        $action = request('action');
        $param = request('param');
        $modal = new FBACustomerReturnAjax();
        return $param ? call_user_func([$modal,$action],$param) : call_user_func([$modal,$action]);
    }

    public function download(){
        $filtersField = array_keys($this->filters);
        $filters = $this->_getFilters($filtersField);
        $query = $this->_initQuery($filters);
        $this->_exeDownload($query);
    }

    private function _exeDownload($query){
        $head = ['账号','SKU','品名','来源','退货时间','国家','purchase_date','订单号','平台SKU','ASIN','FNSKU','数量',
            'detailed_disposition','fulfillment_center_id','主要原因','评论','标签','状态'];
        set_time_limit(0);
        $response = new StreamedResponse(null, 200, [
            'Content-Type'        => 'text/csv;charset=utf-8',
            'Content-Disposition' => 'attachment;filename="退货报表FBA.csv"',
        ]);
        $response->setCallback(function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->chunk(800, function ($re) use ($fp){
                $data = self::getData($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
            fclose($fp);
        });
        $response->send();
        exit(0);
    }

    private static function getData($re){
        $account = [];
        $country = [];
        $sku = [];
        foreach ($re as $row){
            if(!array_key_exists($row->account_id,$account)){
                $account[$row->account_id] = SysPlatAccount::getAccountById($row->account_id);
            }
            if(!array_key_exists($row->country_id,$country)){
                $country[$row->country_id] = SysCountry::getCountryById($row->country_id);
            }
            if(!array_key_exists($row->psku_id,$sku)){
                $sku[$row->psku_id] = ProductSku::getModelById($row->psku_id);
            }
            $_sku = $sku[$row->psku_id];
            $temp = [
                $account[$row->account_id],
                $_sku->psku_code ?? '',
                $_sku->psku_cn ?? '',
                '退货',
                $row->return_date,
                $country[$row->country_id],
                $row->purchase_date,
                $row->order_id,
                $row->sku,
                $row->asin,
                $row->fnsku,
                $row->quantity,
                $row->detailed_disposition,
                $row->fulfillment_center_id,
                $row->reason,
                $row->customer_comments,
                is_null($row->tag) ? '' : implode(',',QDictTag::getTag($row->tag)),
                FbaCustomerReturn::$_status[$row->status],
            ];
            yield $temp;
        }
    }
}
